import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter_fitness/app_controller.dart';
import 'package:flutter_fitness/model/db/record_provider.dart';
import 'package:flutter_fitness/model/entity/record.dart';
import 'package:get/get.dart';

class AddRecordLogic extends GetxController {

  final dateTime = DateTime.now();
  final Rx<Record> _record = Get.find<AppController>().record;
  TextEditingController weightTextController;
  TextEditingController stepTextController;
  RxBool isPray;
  RxBool isRead;
  RxDouble weight;
  RxInt step;

  AddRecordLogic() {
    isPray = _record.value.isPray.obs;
    isRead = _record.value.isRead.obs;
    weight = _record.value.weight.obs;
    step = _record.value.step.obs;
    weightTextController = TextEditingController(text: weight.value < 0 ? "" : weight.value.toString());
    stepTextController = TextEditingController(text: step.value == 0 ? "" : step.value.toString());
  }

  void setIsPray(bool isPray) {
    this.isPray.value = isPray;
    _record.value.isPray = isPray;
  }

  void setIsRead(bool isRead) {
    this.isRead.value = isRead;
    _record.value.isRead = isRead;
  }

  void saveRecord() async {
    try {
      final weightText = weightTextController.text.trim();
      if (weightText.isEmpty)
        _record.value.weight = -1;
      else {
        final weight = double.parse(weightText);
        if (weight < 0) {
          Get.snackbar("提示", "请输入正确的体重");
          return;
        } else
          _record.value.weight = weight;
      }
    } catch (error) {
      Get.snackbar("提示", "请输入正确的体重");
    }
    try {
      final stepText = stepTextController.text.trim();
      if (stepText.isEmpty)
        _record.value.step = 0;
      else {
        final step = int.parse(stepText);
        if (step <= 0) {
          Get.snackbar("提示", "请输入正确的步数");
          return;
        } else
          _record.value.step = step;
      }
    } catch (error) {
      Get.snackbar("提示", "请输入正确的步数");
    }
    final provider = RecordProvider();
    await provider.open();
    bool saveResult = false;
    if (_record.value.id == null) {
      final record = await provider.insert(_record.value);
      saveResult = record.id != null;
    } else {
      final count = await provider.update(_record.value);
      saveResult = count > 0;
    }
    if (saveResult) {
      Get.snackbar("提示", "记录保存成功");
      weight.value = _record.value.weight;
      step.value = _record.value.step;
    } else {
      Get.snackbar("提示", "记录保存失败");
    }
  }

  @override
  void onClose() {
    super.onClose();
    weightTextController.dispose();
    stepTextController.dispose();
  }

}
